/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aplicacao;

import auxiliar.Pagina;
import auxiliar.Quadro;
import hardware.MemoriaPrincipal;
import hardware.MemoriaSecundaria;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author Luan
 */

/*
 * Coloquei no pacote aplicação, mas talvez possa até ser criado um novo pacote
 * pra separar os código de interface da aplicação.
 */
public class TelaPrincipal extends javax.swing.JFrame {

    static BufferedReader in;
    // Constantes que representam as políticas de substituição e os tipos de escopo.
    public static final int POLITICA_FIFO = 0;
    public static final int POLITICA_LRU = 1;
    public static final int ESCOPO_LOCAL = 0;
    public static final int ESCOPO_GLOBAL = 1;
    public static int politica;
    public static int escopo;
    public static int tamEnderecoLogico;

    /**
     * Creates new form Interface
     */
    public TelaPrincipal() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnIniciaSimulador = new javax.swing.JButton();
        tamPagina = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        tamEndLogico = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        tituto = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        tamMemoriaFisica = new javax.swing.JTextField();
        tamMemoriaSec = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        btnSelecArquivo = new javax.swing.JButton();
        txtCaminho = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        comboPolitica = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        comboEscopo = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btnIniciaSimulador.setText("Iniciar Simulador");
        btnIniciaSimulador.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnIniciaSimuladorMouseClicked(evt);
            }
        });
        btnIniciaSimulador.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIniciaSimuladorActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setText("Tamanho da Página:");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel2.setText("Tamanho do Endereço Lógico (em bits):");

        tituto.setFont(new java.awt.Font("Tahoma", 1, 18));
        tituto.setText("Simulador de Memória Virtual");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel3.setText("Tamanho da Memória física:");

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel4.setText("Tamanho Máximo da Memória Secundária:");

        tamMemoriaSec.setToolTipText("");

        jLabel7.setText("Sistemas Operacionais - 2012.1");

        jLabel8.setText("Grupo: Luan Moura, Bruno Schettino e Wladimir Cabral");

        btnSelecArquivo.setText("Selecionar Arquivo de Entrada");
        btnSelecArquivo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnSelecArquivoMouseClicked(evt);
            }
        });

        txtCaminho.setEditable(false);
        txtCaminho.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCaminhoActionPerformed(evt);
            }
        });

        jLabel5.setText("Política de Substituição:");

        comboPolitica.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "FIFO", "LRU" }));
        comboPolitica.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboPoliticaActionPerformed(evt);
            }
        });

        jLabel6.setText("Tipo de Escopo:");

        comboEscopo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Local", "Global" }));

        jLabel9.setText("bytes");

        jLabel10.setText("bytes");

        jLabel11.setText("bytes");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(54, 54, 54)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(tamMemoriaSec, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel11))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(tamPagina, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel9))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                                .addComponent(jLabel3)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(tamMemoriaFisica))
                                            .addComponent(jLabel2))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(tamEndLogico, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(jLabel10))))
                                .addGap(90, 90, 90)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel6)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(comboEscopo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel5)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(comboPolitica, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(286, 286, 286)
                        .addComponent(btnIniciaSimulador))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(214, 214, 214)
                        .addComponent(tituto))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(204, 204, 204)
                        .addComponent(jLabel8)))
                .addContainerGap(110, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 92, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addGap(279, 279, 279))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnSelecArquivo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtCaminho, javax.swing.GroupLayout.PREFERRED_SIZE, 379, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(49, 49, 49))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(tituto, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tamPagina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel5)
                    .addComponent(comboPolitica, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tamEndLogico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(comboEscopo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(tamMemoriaFisica, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(tamMemoriaSec, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtCaminho, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSelecArquivo))
                .addGap(28, 28, 28)
                .addComponent(btnIniciaSimulador)
                .addGap(32, 32, 32))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnIniciaSimuladorMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnIniciaSimuladorMouseClicked
        // Crítica para campos de entrada de dados.
        if (this.tamEndLogico.getText().length() == 0) {
            return;
        }
        try {
            Integer.parseInt(this.tamPagina.getText());
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(rootPane, "Por favor, digite um valor numérico para o tamanho da página.", "Erro", JOptionPane.ERROR_MESSAGE);
            return;
        }
        int tamPaginas = Integer.parseInt(this.tamPagina.getText());
        int tamMemFisica = Integer.parseInt(this.tamMemoriaFisica.getText());
        if (tamMemFisica % tamPaginas != 0) {
            JOptionPane.showMessageDialog(rootPane, "Tamanho da Memória física não é multiplo do tamanho das Páginas.", "Erro", JOptionPane.ERROR_MESSAGE);
            return;
        }
        int tamMemSec = Integer.parseInt(this.tamMemoriaSec.getText());
        if (tamMemSec % tamPaginas != 0) {
            JOptionPane.showMessageDialog(rootPane, "Tamanho da Memória secundária não é multiplo do tamanho das Páginas.", "Erro", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        TelaPrincipal.tamEnderecoLogico = Integer.parseInt(tamEndLogico.getText());

        // Definindo o tamanho das páginas e quadros.
        Pagina.setTAMANHO(tamPaginas);
        Quadro.setTAMANHO(tamPaginas);

        String maximoOffset = Integer.toBinaryString(Pagina.getTAMANHO());
        int bitsOffset = maximoOffset.length();
        if(bitsOffset>TelaPrincipal.tamEnderecoLogico){
            JOptionPane.showMessageDialog(rootPane, "Tamanho do endereço lógico inválido para o tamanho de página escolhido.", "Erro", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // Memória Principal: Definindo a quantidade de quadros e o espaço reservado para as Tabelas de Páginas dos processos
        int qtdQuadrosMP = tamMemFisica / tamPaginas;
        int tamTPMP;
        if ((qtdQuadrosMP) / 8 < 1) {
            tamTPMP = 1;
        } else {
            tamTPMP = (qtdQuadrosMP) / 8;
        }
        MemoriaPrincipal.setTAMANHO(qtdQuadrosMP - tamTPMP);
        MemoriaPrincipal.setEspacoDisponivel(qtdQuadrosMP - tamTPMP);
        MemoriaPrincipal.setTAMANHO_TP(tamTPMP * tamPaginas);
        MemoriaPrincipal.setEspacoDisponivelTP(tamTPMP * tamPaginas);

        // Memória Secundária: Definindo a quantidade de quadros e o espaço reservado para as Tabelas de Páginas dos processos
        int qtdQuadrosMS = tamMemSec / tamPaginas;
        int tamTPMS;
        if ((qtdQuadrosMS) / 8 < 1) {
            tamTPMS = 1;
        } else {
            tamTPMS = (qtdQuadrosMS) / 8;
        }
        MemoriaSecundaria.setTAMANHO(qtdQuadrosMS - tamTPMS);
        MemoriaSecundaria.setEspacoDisponivelTPSec(qtdQuadrosMS - tamTPMS);
        MemoriaSecundaria.setTAMANHO_TP(tamTPMS * tamPaginas);
        MemoriaPrincipal.setEspacoDisponivelTP(tamTPMS * tamPaginas);

        TelaPrincipal.politica = comboPolitica.getSelectedIndex();
        TelaPrincipal.escopo = comboEscopo.getSelectedIndex();

        JFrame telaSimulador = new TelaSimulador();
        telaSimulador.setVisible(true);
        this.setVisible(false);
        telaSimulador.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        TelaSimulador.in = TelaPrincipal.in;
    }//GEN-LAST:event_btnIniciaSimuladorMouseClicked

    private void btnSelecArquivoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnSelecArquivoMouseClicked
        // Escolhendo o arquivo a ser lido.
        InputStream ist;
        JFileChooser m_FileChooser;
        m_FileChooser = new JFileChooser();
        m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        try {
            int nState = m_FileChooser.showOpenDialog(null);
            if (nState == JFileChooser.APPROVE_OPTION) {
                File SelectedFile = m_FileChooser.getSelectedFile();
                ist = new FileInputStream(SelectedFile);
                TelaPrincipal.in = new BufferedReader(new InputStreamReader(ist));
                this.txtCaminho.setText(SelectedFile.getPath());
                this.txtCaminho.setCaretPosition(0);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(TelaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnSelecArquivoMouseClicked

    private void txtCaminhoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCaminhoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCaminhoActionPerformed

    private void btnIniciaSimuladorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIniciaSimuladorActionPerformed
    }//GEN-LAST:event_btnIniciaSimuladorActionPerformed

    private void comboPoliticaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboPoliticaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_comboPoliticaActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new TelaPrincipal().setVisible(true);
            }
        });

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnIniciaSimulador;
    private javax.swing.JButton btnSelecArquivo;
    private javax.swing.JComboBox comboEscopo;
    private javax.swing.JComboBox comboPolitica;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JTextField tamEndLogico;
    private javax.swing.JTextField tamMemoriaFisica;
    private javax.swing.JTextField tamMemoriaSec;
    private javax.swing.JTextField tamPagina;
    private javax.swing.JLabel tituto;
    private javax.swing.JTextField txtCaminho;
    // End of variables declaration//GEN-END:variables
}
